package com.ly.emp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.common.core.utils.BaseUtils;
import com.ly.emp.entity.EpmBaseRel;
import com.ly.emp.entity.EpmBaseSuitunitOrg;
import com.ly.emp.mapper.EpmBaseRelMapper;
import com.ly.emp.service.IEpmBaseRelService;
import com.ly.emp.service.IEpmBaseSuitunitOrgService;
import com.ly.emp.service.IEpmBaseSuitunitService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 绩效考核人员-impl
 *
 * @author luoyun
 * @Date: 2025-05-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EpmBaseRelServiceImpl extends ServiceImpl<EpmBaseRelMapper, EpmBaseRel> implements IEpmBaseRelService {

    private final IEpmBaseSuitunitService baseSuitunitService;
    private final IEpmBaseSuitunitOrgService baseSuitunitOrgService;

    @Override
    public R getId(String id) {
        EpmBaseRel entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getPage(EpmBaseRel entity, Page<EpmBaseRel> page) {
        String suitUnit = BaseUtils.getSuitUnit();
        entity.setSuitUnit(suitUnit);
        String orgCode = entity.getOrgCode();
        List<String> orgCodeList = new ArrayList<>();
        if (StrUtil.isNotEmpty(orgCode)) {
            // 查询当前部门以及全部子部门的
            orgCodeList = this.getOrgCodeListByOrgCode(orgCode, suitUnit);
            entity.setOrgCode(null);
        }
        log.info("全部的子绩效部门code为：{}", orgCodeList);
        IPage<EpmBaseRel> pageList = this.page(
                page,
                new LambdaQueryWrapper<EpmBaseRel>()
                        .like(StrUtil.isNotEmpty(entity.getPsnName()), EpmBaseRel::getPsnName, entity.getPsnName())
                        .eq(StrUtil.isNotEmpty(entity.getOrgCode()), EpmBaseRel::getOrgCode, entity.getOrgCode())
                        .in(CollUtil.isNotEmpty(orgCodeList), EpmBaseRel::getOrgCode, orgCodeList)
                        .eq(StrUtil.isNotEmpty(entity.getIsAssess()), EpmBaseRel::getIsAssess, entity.getIsAssess())
                        .eq(StrUtil.isNotEmpty(entity.getPersonType()), EpmBaseRel::getPersonType, entity.getPersonType())
                        .eq(StrUtil.isNotEmpty(entity.getSuitUnit()), EpmBaseRel::getSuitUnit, entity.getSuitUnit())
                        .orderByAsc(EpmBaseRel::getOrgCode)
                        .orderByAsc(EpmBaseRel::getDisplayOrder)
        );
        return R.ok(pageList);
    }

    /**
     * 查找对应考核组织下的部门并封装自己的后代
     *
     * @param orgCode
     * @param suitUnit
     * @return
     */
    private List<String> getOrgCodeListByOrgCode(String orgCode, String suitUnit) {
        List<String> orgCodeList = new ArrayList<>();
        List<EpmBaseSuitunitOrg> allSuitunitOrgList = baseSuitunitOrgService.list(
                new LambdaQueryWrapper<EpmBaseSuitunitOrg>()
                        .eq(EpmBaseSuitunitOrg::getSuitUnit, suitUnit)
                        .orderByAsc(EpmBaseSuitunitOrg::getOrgCode)
        );
        // 添加全部后代
        this.getOrgCodeList(orgCode, allSuitunitOrgList, orgCodeList);
        // 添加自身
        orgCodeList.add(orgCode);
        return orgCodeList;
    }

    /**
     * 递归查找所有的后代集合
     *
     * @param orgCode
     * @param datas
     * @param orgCodeList
     */
    private void getOrgCodeList(String orgCode, List<EpmBaseSuitunitOrg> datas, List<String> orgCodeList) {
        List<String> childrenOrgCodeList =
                datas.stream()
                        .filter(n -> orgCode.equals(n.getParentOrgCode()))
                        .map(n -> n.getOrgCode()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(childrenOrgCodeList)) {
            orgCodeList.addAll(childrenOrgCodeList);
            // 处理子集的子集
            childrenOrgCodeList.stream().forEach(n -> getOrgCodeList(n, datas, orgCodeList));
        }
    }

    @Override
    public R add(EpmBaseRel entity) {
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }

    @Override
    public R edit(EpmBaseRel entity) {
        boolean flag = this.updateById(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    public R delete(String id) {
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<EpmBaseRel> dto) {
        List<EpmBaseRel> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    public List<EpmBaseRel> getListByEntity(EpmBaseRel entity) {
        LambdaQueryWrapper<EpmBaseRel> queryWrapper = this.getQueryWrapper(entity);
        return this.list(queryWrapper);
    }

    private LambdaQueryWrapper<EpmBaseRel> getQueryWrapper(EpmBaseRel entity) {
        LambdaQueryWrapper<EpmBaseRel> queryWrapper = new LambdaQueryWrapper<EpmBaseRel>()
                .like(StrUtil.isNotBlank(entity.getPsnName()), EpmBaseRel::getPsnName, entity.getPsnName())
                .like(StrUtil.isNotBlank(entity.getOrgName()), EpmBaseRel::getOrgName, entity.getOrgName())
                .eq(StrUtil.isNotBlank(entity.getOrgCode()), EpmBaseRel::getOrgCode, entity.getOrgCode())
                .eq(StrUtil.isNotBlank(entity.getSuitUnit()), EpmBaseRel::getSuitUnit, entity.getSuitUnit())
                .eq(StrUtil.isNotBlank(entity.getUserUnit()), EpmBaseRel::getUserUnit, entity.getUserUnit())
                .eq(StrUtil.isNotBlank(entity.getIsAssess()), EpmBaseRel::getIsAssess, entity.getIsAssess())
                .eq(StrUtil.isNotBlank(entity.getPersonType()), EpmBaseRel::getPersonType, entity.getPersonType())
                .in(CollUtil.isNotEmpty(entity.getPersonTypeList()), EpmBaseRel::getPersonType, entity.getPersonTypeList())
                .in(CollUtil.isNotEmpty(entity.getUserPosTypeList()), EpmBaseRel::getUserPosType, entity.getUserPosTypeList())
                .in(CollUtil.isNotEmpty(entity.getOrgCodeList()), EpmBaseRel::getOrgCode, entity.getOrgCodeList())
                .in(CollUtil.isNotEmpty(entity.getPsnNumList()), EpmBaseRel::getPsnNum, entity.getPsnNumList())
                .notIn(CollUtil.isNotEmpty(entity.getExcludePsnNumList()), EpmBaseRel::getPsnNum, entity.getExcludePsnNumList())
                .orderByAsc(EpmBaseRel::getOrgCode)
                .orderByAsc(EpmBaseRel::getPersonType)
                .orderByAsc(EpmBaseRel::getDisplayOrder);
        return queryWrapper;
    }
}
